<template>
  <div>
    <div ref="initRef"></div>
    <!-- 文章编辑界面 -->
    <Window :show="windowConfig.show"
            :buttons="windowConfig.buttons"
            @close="closeWindow">
      <el-form :model="articleFormData"
               :rules="rules"
               ref="articleFormRef">
        <el-form-item prop="title">
            <div class="title-input">
                <el-input placeholder="请输入文章标题"
                          v-model="articleFormData.title">
                </el-input>
            </div>
            <el-button type="primary" @click="tagsEdit">编辑标签</el-button>
            <el-button type="primary" @click="showAI">AI求助</el-button>
        </el-form-item>
        <el-form-item prop="content">
            <div :style="{'windth':'100%'}">
                <Editor :height="editorHeight"
                        v-model="articleFormData.content"
                        ref="editorRef"></Editor>
            </div>
        </el-form-item>
      </el-form>
    </Window>
    <AdminDialog :show="dialogConfig.show"
            :title="dialogConfig.title"
            :buttons="dialogConfig.buttons"
            width="500px"
            @close="dialogConfig.show=false">
      <Table :columns="columns"
             :showPagination="false"
             :dataSource="tagsData"
             :fetch="loadTagsList"
             :options="tagsOptions"
             @rowSelected="handleRowSelected">
      </Table>
    </AdminDialog>
    <AdminDialog :show="aiConfig.show"
            :title="aiConfig.title"
            width="500px"
            @close="closeAI">
      <el-input v-model="question" placeholder="Enter your question" />
      <el-button type="primary"
                 @click="getAnswer"
                 style="margin-top: 20px;">获取回答</el-button>
                 <div v-if="answerStatus === 'loading'" class="answer-box">
                  <p>AI正在思考</p>
                 </div>
                 <div v-if="answerStatus === 'success'" class="answer-box">
                  <p>{{ answer }}</p>
                 </div>
                 <div v-if="answerStatus === 'error'" class="answer-box">
                  <p>AI出现问题</p>
                 </div>
    </AdminDialog>
  </div>
</template>

<script>
import { columns } from 'element-plus/es/components/table-v2/src/common.mjs';
import Window from '../../components/Window.vue';
import { getCurrentInstance, nextTick, reactive } from 'vue';
export default {
  components: { Window },
  data(){
    return{
        proxy: getCurrentInstance().proxy,
        editorHeight: window.innerHeight - 60 - 20 - 30 - 50 - 100 - 50,
        editType:null,
        articleFormRef:null,
        editorRef:null,
        selectedTagsId:[],
        question:'',
        answer:'',
        answerStatus:'',
        $refs:{
          initRef:null,
        },
        articleFormData:{
        },
        tagsOptions:{
          selectType:'checkbox',
          extHeight:10,
          showIndex:true,
        },
        columns:[{
        label: "标签名称",
        prop: "tagName",
        }],
        windowConfig:{
          show:false,
          buttons:[
            {
              type:"danger",
              text:"发布",
              click: (e) => {
                  console.log("准备发布");
                  this.submitArticle();
              }
            }
          ]
        },
        //tagsData需要置为空通过loadTagsList返回
        //tagsData:null,
        tagsData: {
          list :[]
        },
        dialogConfig: {
          show:false,
          title:"选择标签",
          buttons:[
            {
              type:"primaey",
              text:"确定",
              click: (e) => {
                console.log("发送tag")
                this.choseEnd();
              },
            },
          ],
        },
        aiConfig:{
          show:false,
          title:"AI回答",
        }
    }
  },
  methods:{
    init(type,data){
      this.windowConfig.show = true;
      this.editType = type;
      this.articleFormData = {
        tags: [],
        content: '',
        title: '',
      };
      nextTick(() => {
        if(this.$refs.articleFormRef){
          this.$refs.articleFormRef.resetFields();
        }
        this.articleFormData = {
          tags:[],
          content:'',
          title:'',
        };
        if(type == 'update') {
          this.getArticleDetail(data.id)
        }
      })
    },

    //获取待修改文章
    async getArticleDetail(articleId){
      try{
        let result = await this.proxy.Request({
          url:"/articles/"+articleId,
          method:"GET",
        })
        if(!result){
          return;
        }
        this.articleFormData = result.data
      }catch(error){
        console.error(error)
      }
    },

    //展示并选择标签
    async tagsEdit(){
     this.dialogConfig.show = true;
     try {
       let result = await this.proxy.Request({
         url: "/tags",
         method: "GET"
       });

       if (!result){
         return;
       }
       this.tagsData.list = result.data;
          
          if(this.articleFormData.id){
            let tagResult = await this.proxy.Request({
              url:"/articletags/"+this.articleFormData.id,
              method:DELETE,
            });

            if(!tagResult){
              return;
            }
          }
     } catch(error){
       console.error("获取标签数据时出错：",error)
     }
    },

    handleRowSelected(selectedIds){
        // console.log(selectedIds);
        this.selectedTagsId = selectedIds;
        console.log(this.selectedTagsId);
      },

    //退出标签选择
    choseEnd(){
      this.dialogConfig.show = false;
      if(this.editType === 'update'){
        try{
          let result = this.proxy.Request({
            url:'/articletags/'+this.articleFormData.id+'/'+this.selectedTagsId,
            method:'POST'
          })
          if(!result){
            return;
          }
        }catch(error){
          console.error(error)
        }
      }
    },

    showAI(){
      this.aiConfig.show = true;
    },

    async getAnswer(){
      this.answerStatus = 'loading';
      const formData = new FormData();
      formData.append('question',this.question)
      const url = '/sendQuestion';
      try {
        let result = await this.proxy.Request({
          url: "/sendQuestion",
          method: "POST",
          data:formData,
          headers:{
            'content-type': 'multipart/form-data'
          }
        });
        this.answer = result.data;
        this.answerStatus = 'success';
      } catch(error){
        console.error("获取ai数据时出错：",error)
        this.answerStatus = 'error'
      }
    },

    closeAI(){
      this.aiConfig.show = false;
      this.answerStatus = '';
      this.answer = '';
    },

    //获取文章中的图片
    getImageData(){
      const content = this.articleFormData.content;
      const imageRegex = /<img[^>]+src="([^"]+)"[^>]*>/g;
      const imageData = [];
      let match;
      while ((match = imageRegex.exec(content)) !== null){
        imageData.push(match[1]);
      }
      return imageData;
    },

    //发送编辑文章
    async submitArticle() {
      if (!!this.articleFormData.title && !(this.articleFormData.content.trim() === '<p><br></p>')) {
        console.log(this.editType);
        const imageData = this.getImageData();
        const formData = new FormData();

        // 添加其他字段
        formData.append('title', this.articleFormData.title);
        formData.append('content', this.articleFormData.content);

        // 处理图片文件
        const blobs = await Promise.all(imageData.map(async (imgBlob, index) => {
          const response = await fetch(imgBlob);
          const blob = await response.blob();
          return new File([blob], `image${index}.png`, { type: blob.type });
        }));

        blobs.forEach((file, index) => {
          formData.append('images', file);
        });

        // 添加标签 ID
        this.selectedTagsId.forEach(id => {
          formData.append('tagIds', id);
        });

        // 发送请求
        try {
          let result;
          if (this.editType == "add") {
            const imagesvalue = formData.get("images")
            console.log(imagesvalue)
            result = await this.proxy.Request({
              url: '/articles/create',
              method: "POST",
              headers: {
                'Content-Type': 'multipart/form-data'
              },
              data: formData, // FormData 对象作为请求体
            });
            console.log("where is");
            console.log(result);
            if (!result) {
              return;
            }
            this.proxy.Message.success("发布成功");
            this.closeWindow();
          } else {
            result = await this.proxy.Request({
              url: "/articles/update/" + this.articleFormData.id,
              method: 'PUT',
              headers: {
                'Content-Type': 'multipart/form-data'
              },
              data: formData, // FormData 对象作为请求体
            });
            if (!result) {
              return;
            }
            this.proxy.Message.success("发布成功");
            this.closeWindow();
          }
        } catch (error) {
          console.error(error);
        }
      } else {
        console.log("请编辑文章");
      }
    },

    //关闭编辑窗口
    closeWindow(){
      this.windowConfig.show = false;
      this.$emit("callback");
    },

  },
  mounted(){
    this.$nextTick(() => {
      this.initRef = this.$refs.initRef;  
    })
    
  }
}
</script>

<style>

</style>